<template>
  <d2-container>
    <div class="form-area">
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="rules"
        label-width="140px"
        style="width: 80%; height:auto;"
      >
        <!-- 基本信息 -->
        <div class="form-title">
          <h3>基本信息</h3>
        </div>
<el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购原因简述：" prop="purchaseReason">
              <el-input v-model="addForm.purchaseReason" placeholder="请输入采购原因"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购订单编码：" prop="orderNo">
              <el-input v-model="addForm.orderNo" placeholder="采购订单编码，自动生成" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商名称：" prop="supplierName">
              <el-cascader
                v-model="addForm.supplierId"
                :options="supplierTree"
                :props="{ value: 'id', label: 'supplierName' }"
                @change="handleChangeSupplier"
                placeholder="请选择供应商"
                style="width: 100%;"
              ></el-cascader>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系人：" prop="supplierContact">
              <el-input v-model="addForm.supplierContact" placeholder="请输入供应商联系人" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划到货日期：" prop="expectedArrivalTime">
                <el-date-picker
                  v-model="dateSelect"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库状态：" prop="stockStatus">
              <el-select v-model="addForm.stockStatus" placeholder="未入库" disabled>
                <el-option label="全部" value></el-option>
                <el-option label="未入库" value="1"></el-option>
                <el-option label="部分入库" value="2"></el-option>
                <el-option label="全部入库" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="总金额：" prop="amountTotal">
              <el-input v-model="addForm.amountTotal" placeholder="总金额" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已付金额：" prop="paidAmount">
              <el-input v-model="addForm.paidAmount" placeholder="已付金额" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="未付金额：" prop="toPayAmount">
              <el-input v-model="addForm.toPayAmount" placeholder="未付金额" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款状态：" prop="payStatus">
              <el-select v-model="addForm.payStatus" placeholder="全部" disabled>
                <el-option label="全部" value></el-option>
                <el-option label="未付" value="0"></el-option>
                <el-option label="部分付款" value="1"></el-option>
                <el-option label="已付款" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件/便笺：">
              <el-upload
                :headers="headerParams"
                :action="getUploadUrl()"
                ref="uploadFile"
                :limit="1"
                :on-exceed="handleExceedMainImage"
                :auto-upload="false"
                :on-change="imgPreviewMainImage"
                :accept="'image/*, .pdf, .rar, .zip'"
                list-type="text"
                :show-file-list="true"
                :on-success="handleSuccessMainImage"
                :on-error="handleErrorMainImage"
                :before-remove="handleRemove"
                :file-list="fileList"
              >
                <el-button
                  slot="trigger"
                  size="small"
                  type="primary"
                  @click="clickMainImageSelect"
                >选择附件</el-button>
                <el-button
                  style="margin-left: 10px;"
                  size="small"
                  type="success"
                  @click="submitUploadMainImage"
                >上传到服务器</el-button>

                <div slot="tip" class="el-upload__tip">请上传相关采购文件附件/截图，多个文件请打包上传</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品备注" prop="remark">
              <el-input type="textarea" v-model="addForm.remark" :readonly="isDetails"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="form-title">
          <h3>审核信息</h3>
        </div>
        <el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="提交人" prop="submitor">
              <el-input type="text" v-model="addForm.submitor" placeholder="提交人" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提交时间" prop="submitTime">
              <el-date-picker
                v-model="addForm.submitTime"
                type="datetime"
                placeholder="提交时间"
                readonly
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核人" prop="auditor">
              <el-input type="text" v-model="addForm.auditor" placeholder="审核人" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核时间" prop="authTime">
              <el-date-picker
                v-model="addForm.authTime"
                type="datetime"
                placeholder="审核时间"
                readonly
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核状态" prop="status">
              <el-select v-model="addForm.status" placeholder="全部" disabled>
                <el-option label="全部" value></el-option>
                <el-option label="未提交" value="0"></el-option>
                <el-option label="审核中" value="1"></el-option>
                <el-option label="审核通过" value="2"></el-option>
                <el-option label="审核拒绝" value="3"></el-option>
                <el-option label="采购取消" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核说明" prop="authDesc">
              <el-input
                type="textarea"
                :rows="4"
                v-model="addForm.authDesc"
                placeholder="审核说明"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="form-title">
          <h3>系统信息</h3>
        </div>
        <el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建人" prop="creator">
              <el-input type="text" v-model="addForm.creator" placeholder="创建人" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="addForm.createTime"
                type="datetime"
                placeholder="创建时间"
                readonly
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="修改人" prop="reviser">
              <el-input type="text" v-model="addForm.reviser" placeholder="修改人" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修改时间" prop="reviseTime">
              <el-date-picker
                v-model="addForm.reviseTime"
                type="datetime"
                placeholder="修改时间"
                readonly
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="form-title">
          <h3>采购明细</h3>
        </div>
<el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <template>
              <div class="table-header">
                <el-button type="primary" @click="showProductPage()">添加采购明细</el-button>
                <el-alert
                  title="注意：只允许添加同一个供应商商品"
                  type="info"
                  style="width: 300px; margin-left: 20px;"
                ></el-alert>
              </div>
              <div class="form-table">
                <el-table :data="tableDetailList" stripe border style="width: 100%">
                  <el-table-column type="index" fixed label="序号" width="50"></el-table-column>
                  <el-table-column label="SPU商品" prop="productName"></el-table-column>
                  <el-table-column label="SKU商品" prop="productSkuName"></el-table-column>
                  <el-table-column label="采购数量" prop="purchaseQuantity">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.purchaseQuantity"
                        clearable
                        placeholder="填写数量"
                        @blur="setQuantity(scope.$index, scope.row)"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="采购单位" prop="unitName">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.unitId" placeholder="请选择" @focus="getProductUnitList(scope.row)">
                        <el-option
                          v-for="item in scope.row.unitList"
                          :key="item.id"
                          :label="item.unitName"
                          :value="item.id"
                          >
                            {{ item.label }}{{ item.unitName }} (转换系数：{{ item.ratio }}
                            <span v-if="item.isSkuPack == 1">入库单位</span>
                            <span>)</span>
                        </el-option>
                      </el-select>
                    </template>

                  </el-table-column>
                  <el-table-column label="采购单价（元）" prop="purchasePrice">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.purchasePrice"
                        clearable
                        placeholder="填写单价"
                        @blur="setPrice(scope.$index, scope.row)"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="采购金额（元）" prop="purchaseAmount"></el-table-column>
                  <el-table-column label="折扣(%)" prop="discountRate" :formatter="formatPercent">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.discountRate"
                        clearable
                        placeholder="1~100"
                        @blur="setDiscount(scope.$index, scope.row)"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="折后金额（元）" prop="purchaseAmountDiscount"></el-table-column>
                  <el-table-column label="已入库数量" prop="stockInQuantity"></el-table-column>
                  <!-- 2022-03-17保存接口没有处理删除功能，暂时屏蔽不允许删除 -->
                  <!-- <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button
                        plain
                        type="primary"
                        size="small"
                        @click.native.prevent="deleteRow(scope.$index, scope.row)"
                      >移除</el-button>
                    </template>
                  </el-table-column> -->
                </el-table>
              </div>
            </template>
          </el-col>
        </el-row>

        <!-- 保存 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item>
              <div class="form-submit">
                <el-button class="form-submit-btn" :disabled="loading" type="primary" @click="onSave('addForm', 0)" >保存</el-button>
                <el-button class="form-submit-btn" :disabled="loading" type="primary" @click="onSaveAndSubmit('addForm')" >保存并提交</el-button>
                <el-button class="form-cancle-btn" :disabled="loading" @click="cancel()" >取消</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 弹框-添加采购明细 -->
    <template>
      <el-dialog
        title="添加采购商品"
        width="60%"
        :visible.sync="showProductList"
        :before-close="handleClose"
      >
        <div class="dialog-search">
          <el-form class="inline-form" :inline="true" :model="searchProductForm">
            <el-form-item label="商品名称">
              <el-input
                v-model="searchProductForm.productName"
                placeholder="请输入商品名称"
                style="width: 350px"
              ></el-input>
            </el-form-item>
            <el-button type="primary" size="medium" @click="fetchDataProduct">搜索</el-button>
          </el-form>
        </div>

        <div class="form-table">
          <el-table :data="tableDataProduct" stripe border style="width: 100%">
            <el-table-column prop="index" label="序号" width="50" type="index"></el-table-column>
            <el-table-column prop="thumbImage" label="商品图片" width="50">
              <template slot-scope="scope">
                <el-image style="width: 35px; height: 35px" :src="scope.row.thumbImage"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="SPU商品名称"></el-table-column>
            <el-table-column prop="productSkuCode" label="SKU商品编码"></el-table-column>
            <el-table-column prop="skuName" label="SKU商品名称"></el-table-column>
            <el-table-column prop="" label="商品分类" :formatter="forCategoryName" width="300"></el-table-column>
            <el-table-column prop="status" label="SKU状态" width="80">
              <template slot-scope="scope">
                <span v-if="scope.row.status == 0">下架</span>
                <span v-if="scope.row.status == 1">上架</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button type="primary" plain size="small"
                  v-if="!scope.row.isSeleted"
                  @click="scope.row.isSeleted = true"
                >选择</el-button>
                <el-button type="primary" size="small"
                  v-if="scope.row.isSeleted && !scope.row.isDisabled"
                  @click="scope.row.isSeleted = false"
                >已选</el-button>
                <el-button type="primary" size="small"
                  disabled="scope.row.isDisabled"
                  v-if="scope.row.isDisabled"
                  @click="scope.row.isSeleted = false"
                >已选</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="page dialog-page">
          <el-pagination
            background
            @current-change="handleCurrentChangePurchasePaln"
            :current-page="currentPageProduct"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSizeProduct"
            layout="total, prev, pager, next"
            :total="totalProduct"
          ></el-pagination>
        </div>

        <div class="dialog-footer" slot="footer">
          <el-button type="primary" @click="confirmProduct()">确定</el-button>
          <el-button @click="closeProductList()">取消</el-button>
        </div>
      </el-dialog>
    </template>
  </d2-container>
</template>

<script>
import dayjs from "dayjs";
import util from "@/libs/util";
import { mapActions, mapState } from 'vuex'
import { getOrderInfo, listOrderDetail, saveOrder } from "@api/purchase/purchase";
import { findAllListEnable } from "@api/supplier/supplier";
import { uploadImageUrl } from "@api/common/common";
import { findProductUnitListByProductId } from "@api/product/product"; 
import { findPurchaseProductSkuListByPage } from "@api/product/productSku"; 


export default {
  components: {},
  props: {
    isDetails: {
      type: Boolean,
      default: false
    },
    productDetails: Object
  },
  data() {
    return {
      supplierTree: [], //供应商下拉框
      unitList: [],     //采购单位下拉框
      
      dateSelect: "", //日期控件

      isSubmit: false,  //用于解决提交时，重新赋值unitId导致触发查询的问题

      showProductList: false,

      fileList: [],

      preSupplierId: "",  //缓存切换前的供应商ID

      addForm: {
        ifSubmit: 0,    // 保存时是否提交
        id: "",
        purchaseReason: "",
        orderNo: "",
        supplierId: "",
        supplierName: "",
        supplierContact: "",
        supplierContactPhone: "",
        expectedArrivalTime: "",
        contractUrl: "",
        status: "0",
        stockStatus: "0",
        payStatus: "0",
        amountTotal: "0",
        paidAmount: "0",
        toPayAmount: "0",
        remark: "",
        submitor: "",
        submitTime: "",
        auditor: "",
        authTime: "",
        authDesc: "",
        creator: "",
        createTime: "",
        reviser: "",
        reviseTime: "",
        detailList: [] //用于提交采购明细
      },

      tableDetailList: [],

      searchProductForm: {
        productName: ""
      },
      currentPageProduct: 1,
      pageSizeProduct: 10,
      totalProduct: 0,
      productIds: "",

      tableDataProduct: [], //商品选择

      // 上传图片的请求头，异步提交使用
      headerParams: {
        client_id: "",
        democracy: ""
      },

      // 表单验证规则
      rules: {
        purchaseReason: [
          { required: true, message: "请输入采购原因简述", trigger: "blur" },
          { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" }
        ],
        supplierName: [
          { required: true, message: "请选择供应商", trigger: "blur" }
        ],
        expectedArrivalTime: [
          { required: true, message: "请选择计划到货日期", trigger: "blur" }
        ]
      },

      loading: false,
      isReturnList: false, // 关闭页面是否返回列表

      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < (Date.now() - 3600 * 1000 * 24);
        },
        shortcuts: [
          {
            text: "明天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      }
    };
  },
  watch: {
   
  },
  computed: {
    ...mapState('d2admin/page', ['opened', 'current'])
  },
  methods: {
    ...mapActions('d2admin/page', ['close']),

    // 商品信息start
    // 供应商列表
    getSupplierList() {
      findAllListEnable({ parentId: 0 })
        .then(res => {
          this.supplierTree = res.data;
        })
        .catch(err => {
          console.log("err", err);
        });
    },
    getPurchaseOrder(orderId) {
      getOrderInfo({
          orderId: orderId
      })
          .then((res) => {
              this.addForm.id = res.data.id;
              this.addForm.purchaseReason = res.data.purchaseReason;
              this.addForm.orderNo = res.data.orderNo;
              this.addForm.supplierId = res.data.supplierId;
              this.addForm.supplierName = res.data.supplierName;
              this.addForm.supplierContact = res.data.supplierContact;
              this.addForm.supplierContactPhone = res.data.supplierContactPhone;
              this.addForm.expectedArrivalTime = res.data.expectedArrivalTime;
              this.addForm.contractUrl = res.data.contractUrl;
              this.addForm.status = res.data.status;
              this.addForm.stockStatus = res.data.stockStatus;
              this.addForm.payStatus = res.data.payStatus;
              this.addForm.amountTotal = res.data.amountTotal;
              this.addForm.paidAmount = res.data.paidAmount;
              this.addForm.toPayAmount = res.data.toPayAmount;
              this.addForm.remark = res.data.remark;
              this.addForm.submitor = res.data.submitor;
              this.addForm.submitTime = res.data.submitTime;
              this.addForm.auditor = res.data.auditor;
              this.addForm.authTime = res.data.authTime;
              this.addForm.authDesc = res.data.authDesc;

              this.addForm.creator = res.data.creator;
              this.addForm.createTime = res.data.createTime;
              this.addForm.reviser = res.data.reviser;
              this.addForm.reviseTime = res.data.reviseTime;

              this.addForm.status = this.addForm.status.toString();
              this.addForm.payStatus = this.addForm.payStatus.toString();
              this.addForm.stockStatus = this.addForm.stockStatus.toString(); 
              this.dateSelect = dayjs(this.addForm.expectedArrivalTime).format("YYYY-MM-DD"); 

              this.preSupplierId = res.data.supplierId;

              if(this.addForm.contractUrl != "" && this.addForm.contractUrl != undefined) {
                this.fileList.push({
                    name: res.data.contractUrl,
                    url: res.data.fullContractUrl
                })
              }
          })
          .catch((err) => {
              console.log("err", err);
              this.loading = false 
          });
      
    },
    getPurchaseOrderDetailList(orderId) {   
      listOrderDetail({ orderId: orderId, ifNeedUnitList: 1 })
        .then(res => {
          if (res.code == "000000") {

              this.tableDetailList = res.data;

              this.$set(this.addForm,"detailList", []);      //查询主表时，会覆盖该属性，需要重新赋值

              this.loading = false;
          }
        })
        .catch(err => {
          console.log("err", err);
          this.loading = false;
        });
    },
    handleChangeSupplier(value) {
      // 选择供应商
      let supplierIdValue = value[value.length - 1];

      if(this.preSupplierId != "" && this.preSupplierId != supplierIdValue) {
        this.$confirm("切换供应商，会清空采购明细，是否继续？").then(_ => {
          
          this.tableDetailList.splice(0, this.tableDetailList.length);
       
          this.addForm.amountTotal = 0;
          this.addForm.toPayAmount = 0;
          this.preSupplierId = "";

          this.setSupplierInfo(supplierIdValue);

        }).catch(err => {
          this.addForm.supplierId = this.preSupplierId;
          console.log("this.addForm.supplierId", this.addForm.supplierId);
          console.log("preSupplierId", this.preSupplierId);
          return;
        });
      } 

      // 注意：确认框为异步弹出，此处代码肯定会执行
      if(this.preSupplierId == "") {
        this.setSupplierInfo(supplierIdValue);
      }
    },
    setSupplierInfo(supplierIdValue) {
      //console.log("供应商赋值", this.addForm.supplierId);

      this.addForm.supplierId = supplierIdValue;

      for (var supplier of this.supplierTree) {
        if (supplier.id == this.addForm.supplierId) {
          this.addForm.supplierId = supplier.id;
          this.addForm.supplierCode = supplier.supplierCode;
          this.addForm.supplierName = supplier.supplierName;
          this.addForm.supplierContact = supplier.personInCharge;
          this.addForm.supplierContactPhone = supplier.phone;

          this.preSupplierId = supplier.id;
        }
      }
    },

    handleRemove(file, fileList) {
      // 删除附件
      this.fileList = [];
    },
    // 上传凭证
    getUploadUrl() {
      return uploadImageUrl() + "?type=5";
    },
    imgPreviewMainImage(file, fileList) {
      console.log("文件预览", "待开发");
    },
    handleSuccessMainImage(response, file, fileList) {
      
      console.log("response:", response);
      
      if (response.code == "000000") {
        this.$message.success("上传文件成功");

        this.addForm.contractUrl = response.data;

        this.fileList.push({
            name: this.addForm.contractUrl,
            url: this.addForm.fullContractUrl
        })

        this.mainImageCanCollecting = false;
      } else {
        this.$message.error("上传文件失败:" + response.message);
      }
      fileList.splice(0);
    },
    handleErrorMainImage(err, file, fileList) {
      this.$message.error("上传失败,请重新上传!" + err);
      fileList.splice(0);
    },
    handleExceedMainImage(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    submitUploadMainImage() {
      this.$refs.uploadFile.submit();
    },

    clickMainImageSelect() {
      this.mainImageCanCollecting = true;
    },

    // -----------------------   开始处理采购明细   ---------------------------
    showProductPage() {
      if (this.addForm.supplierId == "") {
        this.$message.warning("请先选择供应商");
        return false;
      }
      this.fetchDataProduct();
      this.showProductList = true;
    },
    fetchDataProduct() {
      this.loading = true;
      findPurchaseProductSkuListByPage({
        purchaseOrderId: this.addForm.id,
        supplierId: this.addForm.supplierId,
        productName: this.searchProductForm.productName,
        currentPage: this.currentPageProduct,
        pageSize: this.pageSizeProduct
      })
        .then(res => {
          for (let index in res.data.content) {
            let sku = res.data.content[index];
            sku.isSeleted = false;
            sku.isDisabled = false;
            
            for (let rowIndex in this.tableDetailList) {
              let row = this.tableDetailList[rowIndex];
              if(row.productSkuId == sku.skuId) {
                sku.isSeleted = true;
                sku.isDisabled = true;
              }
            }
          }
          this.tableDataProduct = res.data.content;
          this.totalProduct = res.data.total;
          this.loading = false;
        })
        .catch(err => {
          console.log("err", err);
          this.loading = false;
        });
    },
    getProductUnitList(row) {
      //优化查询次数，切换一次SPU查一次
      if(row.unitList.length > 0 && row.productId == row.unitList[0].productId) {
        return;
      }

      if(this.unitList.length > 0 && row.productId == this.unitList[0].productId && row.unitList.length == 0) {
        row.unitList = this.unitList;
        return;
      }

      if(this.isSubmit) {
        return;
      }

      findProductUnitListByProductId(
        { productId: row.productId }
        )
        .then(res => {
          // this.$set(row, "unitList", res.data);
          this.unitList = res.data;
          row.unitList = res.data;
        })
        .catch(err => {
          console.log("err", err);
        });
    },
    handleChangeUnit(value) {
      // console.log("value", value);

      // var selectedUnitId = value[value.length - 1];
    },
    // 选择商品后，构建采购明细
    confirmProduct() {
      var skuStr = "";
      for (let i in this.tableDataProduct) {
        let row = this.tableDataProduct[i];
        if (row.isSeleted == true) {
          for (let index in this.tableDetailList) {
            if (this.tableDetailList[index].productSkuId == row.skuId) {
              this.$message({
                message: "商品" + row.skuName + "已存在，请不要重复选择",
                type: "warning"
              });
              return;
            }
          }

          skuStr += "," + row.skuId;

          this.tableDetailList.push({
            productId: row.productId,
            productSkuId: row.skuId,
            // unitId: 0,
            unitName: row.unitName,
            productName: row.productName,
            productSkuName: row.skuName,
            purchaseQuantity: '',
            purchasePrice: '',
            purchaseAmount: 0,
            discountRate: 100,
            purchaseAmountDiscount: 0,
            stockInQuantity: 0,
            unitList: []
          });
        }
      }
      skuStr = skuStr.slice(1);
      if (skuStr == "") {
        this.$message({ message: "请选择待采购商品", type: "warning" });
        return;
      }
      this.closeProductList();
    },
    // 提交
    onSaveAndSubmit(formName) {
      this.onSave(formName, 1);
    },
    // 提交
    onSave(formName, ifSubmit) {
      this.$refs[formName].validate(valid => {
        if (valid) {
     
          let number = 0;
          for (let index in this.tableDetailList) {
            number ++;
            let row = this.tableDetailList[index];
            if (row.purchaseQuantity === "" || row.unitId === "" || row.purchasePrice === "" || row.discountRate === "" ) {
              this.$message({ message: "第[" + number + "]行采购明细未填写完成", type: "warning" });
              return;
            }
          }

          this.loading = true;
          this.isSubmit = true;

          this.addForm.expectedArrivalTime = this.dateSelect;

          if(this.fileList.length == 0) {
            this.addForm.contractUrl = "";
            // console.log("fileList000", this.fileList);
          }
              
          this.addForm.detailList = []
          for (let index in this.tableDetailList) {
            let row = this.tableDetailList[index];

            this.addForm.detailList.push({
              id: row.id,
              productId: row.productId,
              productSkuId: row.productSkuId,
              unitId: row.unitId,
              // unitName: row.unitName,
              // productName: row.productName,
              // productSkuName: row.productSkuName,
              purchasePrice: row.purchasePrice,
              purchaseQuantity: row.purchaseQuantity,
              discountRate: row.discountRate
              // purchaseAmount: row.purchaseAmount,
              // purchaseAmountDiscount: row.purchaseAmountDiscount,
              // stockInQuantity: row.stockInQuantity
              // unitList: row.unitList
            })
          }

          this.addForm.ifSubmit = ifSubmit;

          // 提交表单
          saveOrder(this.addForm)
            .then(res => {
              this.$message.success("保存成功");

              this.loading = false;
              this.isSubmit = false;

              this.cancel();
            })
            .catch(() => {
              this.loading = false;
              this.isSubmit = false;
              // this.gotoNext = false;
            });
        } else {
          this.loading = false;
          this.isSubmit = false;
          // this.gotoNext = false;
        }
      });
    },
    forCategoryName(row) {
      return row.firstLevelName + "/" + row.secondLevelName + "/" + row.thirdLevelName
    },
    //2022-03-17保存接口没有处理删除功能，暂时屏蔽不允许删除
    // deleteRow(index, row) {
    //   this.$confirm("确认移除【" + row.productSkuName + "】吗？").then(_ => {
    //     for (var i = 0; i < this.tableDetailList.length; i++) {
    //       if (i == index) {
    //         this.tableDetailList.splice(i, 1);
    //         // 刷新进货总金额
    //         this.setPurchaseAmountTotal();
    //         break;
    //       }
    //     }
    //   });
    // },
    formatPercent(row, column) {
      return row.discountRate + "%";
    },
    setQuantity(index, row) {
   
      if (row.purchaseQuantity === "") {
        this.$message.warning("采购数量不能为空");
        return false;
      }
      let boolean = new RegExp("^[1-9][0-9]*$").test(row.purchaseQuantity);
      if (!boolean) {
        this.$message.warning("数量必须是正整数");
        row.purchaseQuantity = "";
        return false;
      }
      if (row.purchaseQuantity <= 0) {
        this.$message.warning("采购数量必须大于0");
        row.purchaseQuantity = "";
        return false;
      }

      this.setPurchaseAmount(index, row);
      // 刷新进货总金额
      this.setPurchaseAmountTotal();
    },
    setPrice(index, row) {
   
      if (row.purchasePrice === "") {
        this.$message.warning("采购单价不能为空");
        return false;
      }
      let boolean = new RegExp("^[0-9]+(.[0-9]{1,2})?$").test(row.purchasePrice);
      if (!boolean) {
        this.$message.warning("采购单价必须是数字，最多2位小数");
        row.purchaseQuantity = "";
        return false;
      }
      if (row.purchasePrice <= 0) {
        this.$message.warning("采购单价必须大于0");
        row.purchaseQuantity = "";
        return false;
      }

      this.setPurchaseAmount(index, row);
      // 刷新进货总金额
      this.setPurchaseAmountTotal();
    },
    setDiscount(index, row) {
      
      if (row.discountRate === "") {
        this.$message.warning("折扣比例不能为空");
        row.discountRate = 100;
        return false;
      }
      let boolean = new RegExp("^[0-9]+(.[0-9]{1,2})?$").test(row.discountRate);
      if (!boolean) {
        this.$message.warning("折扣比例必须是数字，最多2位小数");
        row.discountRate = 100;
        return false;
      }
      if (row.discountRate <= 0 || row.discountRate > 100) {
        this.$message.warning("折扣比例必须大于0且小于等于100");
        row.discountRate = 100;
        return false;
      }

      this.setPurchaseAmount(index, row);
      // 刷新进货总金额
      this.setPurchaseAmountTotal();
    },
    setPurchaseAmount(index, row) {
      let purchaseAmount = 0;
      let purchaseAmountDiscount = 0;

      purchaseAmount = (row.purchaseQuantity * row.purchasePrice).toFixed(2);
      purchaseAmountDiscount = (purchaseAmount * row.discountRate / 100).toFixed(2);

      this.$set(row, "purchaseAmount", purchaseAmount);
      this.$set(row, "purchaseAmountDiscount", purchaseAmountDiscount);
    },
    setPurchaseAmountTotal() {
      let purchaseAmountTotal = 0;
      for (let i in this.tableDetailList) {
        let purchaseAmountDiscount = this.tableDetailList[i].purchaseAmountDiscount;
        if (purchaseAmountDiscount == undefined) {
          purchaseAmountDiscount = 0;
        } else {
          purchaseAmountDiscount = parseFloat(purchaseAmountDiscount);
        }
        purchaseAmountTotal = purchaseAmountTotal + purchaseAmountDiscount;
      }
      this.addForm.amountTotal = parseFloat(purchaseAmountTotal).toFixed(2);
      this.addForm.toPayAmount = this.addForm.amountTotal;
    },
    

    handleSizeChangePurchasePaln(val) {
      this.pageSizeProduct = val;
      this.fetchDataProduct();
    },
    handleCurrentChangePurchasePaln(val) {
      this.currentPageProduct = val;
      this.fetchDataProduct();
    },
    closeProductList() {
      this.searchProductForm = {
        supplierId: this.addForm.supplierId,
        productName: ""
      };
      this.showProductList = false;
    },
    handleClose(done) {
      this.searchProductForm = {
        supplierId: this.addForm.supplierId,
        purchasePlanNo: "",
        productName: ""
      };
      done();
    },

    // 返回列表
    closePage() {
      this.$emit("close");
    },
    cancel () {
      // 关闭当前窗口
      this.isReturnList = true
      let tagName = this.current
      this.close({ tagName })
    },
  },
  
  created() {

  },
  mounted() {

    this.loading = true;
    this.getSupplierList();

    let orderId = sessionStorage.getItem('purchaseOrderId');
    
    this.getPurchaseOrder(orderId);
    this.getPurchaseOrderDetailList(orderId);

    // 上传图片插件的请求头
    let getId = util.cookies.get("client");
    let client_id;
    let getId2_reverse = getId.substring(0, 6);
    let getId2 = getId2_reverse
      .split("")
      .reverse()
      .join(""); // 后6位
    let getId1 = getId.substring(6, 13); // 前7位
    client_id = "client" + getId1 + getId2;

    let democracy = util.cookies.get("democracy");

    this.headerParams.clientId = client_id;
    this.headerParams.democracy = democracy;
  },
  
  beforeDestroy () {
    if (this.isReturnList) {
      this.$router.push('/purchase/index')
    }
  }
};
</script>

<style scoped>
.step {
  width: 80%;
  padding: 20px 0 40px 0;
}
.step-title {
  cursor: pointer;
}
::v-deep .image-placeholder {
  width: 50px;
  height: 50px;
  align-items: center;
  justify-content: center;
  background-color: #eee;
  display: flex;
}

::v-deep .edui-editor-iframeholder.edui-default {
  height: 300px !important;
}

#myImage {
  background-color: #6b116b;
  width: 80px;
  height: 32px;
  padding-top: 8px;
  padding-left: 8px;
  border-color: white;
}
.addMyImage {
  background-color: #b24cff;
  width: 104px;
  height: 32px;
  padding-top: 8px;
  padding-left: 12px;
  border: 0px solid white;
}
.addMyImage:hover {
  background-color: #b24cff;
}
.addNotMyImage {
  background-color: #ccc;
}
.addNotMyImage:hover {
  background-color: #ccc;
}

.table-header {
  display: flex;
}
</style>
